
package com.liangtian.mdm.dm.model.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.liangtian.mdm.base.controller.BaseController;
import com.liangtian.mdm.base.utils.ResultObject;
import com.liangtian.mdm.base.utils.ShiroSessionUtils;
import com.liangtian.mdm.base.utils.StandService;
import com.liangtian.mdm.dm.attribute.service.AttributeService;
import com.liangtian.mdm.dm.common.pojo.ResponseMsg;
import com.liangtian.mdm.dm.common.util.RequestUtils;
import com.liangtian.mdm.dm.config.model.AttrConfig;
import com.liangtian.mdm.dm.listener.CacheUtil;
import com.liangtian.mdm.dm.model.model.Model;
import com.liangtian.mdm.dm.model.service.ModelService;
import com.liangtian.mdm.dm.sql.service.GenTableService;
import com.liangtian.mdm.system.log.service.SysLogService;
import com.liangtian.mdm.system.user.model.SysUser;
import com.liangtian.mdm.util.ConstantBean;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/modelController")
public class ModelController extends BaseController {

    @Autowired
    private ModelService modelService;
    @Autowired
    AttributeService attributeServiceImp;
    //@Autowired
    //private AttrGroupService attrGroupService;
    @Autowired
    private GenTableService genTableService;

    @Autowired
    SysLogService sysLogServiceImpl;

    @Autowired
    private CacheUtil cacheUtil;

    //Session中保存的当前登录用户的信息
    //@Value("${ConstantBean.CURRENT_SESSION_USER}")
    //private String ConstantBean.CURRENT_SESSION_USER;

    /**
     * <p>Description: 模型模块根据条件查询数据 </p>
     *
     * @author : xiaoliu
     * @date :2016年9月29日上午9:18:20
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(value = "/queryAllModelList", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject queryAllModelList(HttpServletRequest request, Model model) {
        Map paramMap = RequestUtils.paramToMap(request, Model.class, false);
        PageInfo pageInfo = modelService.queryAllModelListByCondition(paramMap);
        List l = pageInfo.getList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);// JSONArray
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    /**
     * <p>Description: 模型的新增方法 </p>
     *
     * @author : xiaoliu
     * @date :2016年9月29日上午9:19:21
     */
    @RequestMapping(value = "/insertModel", method = RequestMethod.POST)
    @ResponseBody
    public ResultObject insertModel(Model model, HttpServletRequest request) {
        // 获取session中用户
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        model.setCreaterId(String.valueOf(user.getUserId()));// 用户创建ID
        model.setCreaterName(user.getUserName());// 用户创建名称
        model.setVersion(0);// 创建时，模型版本默认为0
        model.setIsTableCreate(0);// 是否创建表 默认为否“0”
        model.setIsJspCreate(0);// 是否创建页面 默认为否“0”
        model.setIsMenuCreate(0);
        model.setStatus("0");// 创建时，状态默认为“0”
        if (model.getIsSubtable() == null) {//如果是否从表字段为“1”
            model.setIsSubtable(0);
        }
        if (model.getIsMoreView() == null) {//如果是多视图字段为“1”
            model.setIsMoreView(0);
        }
        if (model.getClassType().equals("0")) {//如果是列表
            model.setMaintableId(model.getMaintableId());
        } else if (model.getClassType().equals("1")) {//父子树
            model.setMaintableId("");
        } else {//列表树
            model.setMaintableId(model.getMaintableId());
        }
        int count = modelService.insertModel(model);
        ResultObject resultObject = new ResultObject(count, "新增成功", "新增失败");
        return resultObject;
    }

    /**
     * <p>Description: 模型的修改功能 </p>
     *
     * @author : xiaoliu
     * @date :2016年9月29日上午9:21:43
     */
    @ResponseBody
    @RequestMapping(value = "/modelUpdate", method = RequestMethod.POST)
    public JSONObject UpdateModel(Model model) {
        Model mo_del = modelService.selectByPk(model.getId());
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);//获取当前登录人的信息
        model.setUpdaterId(String.valueOf(user.getUserId()));// 默认将当前登录人信息userid付给修改人id
        model.setUpdaterName(user.getUserName());// 默认将当前登录人信息username付给修改人name
        if (null == mo_del.getVersion()) {//如果，模型的版本号的是空
            model.setVersion(1);//修改，初始值赋值 1
        } else {
            int y = Integer.valueOf(mo_del.getVersion()) + 1;//否则，原有版本号的基础上加1
            model.setVersion(y);
        }
        ResponseMsg<String> rMsg = new ResponseMsg<String>();
        try {
            if (model.getIsSubtable() == null) {//如果是否从表字段为“1”
                model.setIsSubtable(0);
            }
            if (model.getIsMoreView() == null) {//如果是多视图字段为“1”
                model.setIsMoreView(0);
            }
            if (model.getClassType().equals("0")) {//如果是列表
                model.setMaintableId(model.getMaintableId());
            } else if (model.getClassType().equals("1")) {//父子树
                model.setMaintableId("");
            } else {//列表树
                model.setMaintableId(model.getMaintableId());
            }
            modelService.updateModel(model);
            rMsg.setRspCode(0);
        } catch (Exception e) {
            e.printStackTrace();
            rMsg.setRspCode(-1);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rMsg", rMsg);
        return jsonObject;
    }

    /**
     * <p>Description: 查询符合条件的model模型 </p>
     *
     * @author : xiaoliu
     * @date :2016年9月29日上午9:26:57
     */
    @RequestMapping(value = "/queryTables", method = RequestMethod.POST)
    @ResponseBody
    public String queryTables(Model model) {
        List<Model> modelList = modelService.queryTables(model);
        return JSON.toJSONString(modelList);
    }

    /**
     * <p>Description: 根据模型id(主键)获取到具体的某一个模型对象</p>
     */
    @ResponseBody
    @RequestMapping(value = "/selectModelById", method = RequestMethod.POST)
    public JSONObject selectModelById(Model model) {
        JSONObject jsonObject = new JSONObject();
        Model m = null;
        try {
            m = modelService.selectByPk(model.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        jsonObject.put("mo", m);
        return jsonObject;
    }

    /**
     * <p>Description:编辑页面的校验，名称是否已经存在 </p>
     *
     * @author : xiaoliu
     * @date :2016年9月29日上午9:31:20
     */
    @ResponseBody
    @RequestMapping(value = "/checkModelNameTwo", method = RequestMethod.POST)
    public JSONObject checkModelNameTwo(Model model) {
        JSONObject jsonObject = new JSONObject();
        int i = modelService.checkModelName(model);
        jsonObject.put("flag", i);
        return jsonObject;
    }

    /**
     * <p>Description: model新增页面，模型名称的校验 </p>
     *
     * @author : xiaoliu
     * @date :2016年9月29日上午9:32:12
     */
    @ResponseBody
    @RequestMapping(value = "/checkModelName", method = RequestMethod.POST)
    public JSONObject checkModelName(HttpServletRequest request, Model model) {
        JSONObject jsonObject = new JSONObject();
        ResponseMsg<String> rMsg = new ResponseMsg<String>();
        try {
            int count = modelService.checkModelName(model);
            rMsg.setRspCode(count);
        } catch (Exception e) {
            e.printStackTrace();
        }
        jsonObject.put("rmsg", rMsg);
        return jsonObject;
    }

    /**
     * 模型的物理删除功能
     *
     * @author : xiaoliu
     * @date :2016年9月29日上午9:20:29
     */
    @ResponseBody
    @RequestMapping(value = "/modelDel", method = RequestMethod.POST)
    public JSONObject modelDel(HttpServletRequest request, String[] ids) {// ids是前台复选框选择的List集合
        JSONObject jsonObject = new JSONObject();
        int t = 0;
        try {
            t = modelService.modelDel(ids);
            jsonObject.put("msg", "success");
        } catch (Exception e) {
            jsonObject.put("msg", "false");
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * 已经建表，逻辑删除数据
     *
     * @author : xiaoliu
     * @date :2016年9月29日上午9:33:10
     * =====
     * 刘晶 == 2017-7-6 8:51am 此方法，目前注销啦，不使用
     * =====
     */
    @ResponseBody
    @RequestMapping(value = "/editByID", method = RequestMethod.POST)
    public JSONObject editByID(HttpServletRequest request, String[] ids) {// ids是前台复选框选择的List集合
        JSONObject jsonObject = new JSONObject();
        int t = 0;
        try {
            List<String> idsLst = Arrays.asList(ids);
            t = modelService.editByID(idsLst);
            for (int i = 0; i < ids.length; i++) {
                genTableService.dropTable(ids[i]);//删除表
            }
            jsonObject.put("msg", "success");
        } catch (Exception e) {
            jsonObject.put("msg", "false");
            e.printStackTrace();
        }
        return jsonObject;
    }

    //模型复制
    @ResponseBody
    @RequestMapping(value = "/modelCopy", method = RequestMethod.POST)
    public JSONObject modelCopy(HttpServletRequest request) {// ids是前台复选框选择的List集合
        JSONObject jsonObject = new JSONObject();
        int t = 0;
        try {
            String oldModelId = request.getParameter("modelId");
            String modelName = request.getParameter("modelName");
            Model addModel = new Model();
            addModel.setModelName(modelName);
            int addcount = modelService.checkModelName(addModel);
            if (addcount > 0) {//说明有重复
                jsonObject.put("msg", "chongfu");
            } else {
                //旧模型
                Model oldModel = modelService.selectByPk(oldModelId);
                Model model = new Model();//创建一个新模型
                // 获取session中用户
                SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
                model.setCreaterId(String.valueOf(user.getUserId()));// 用户创建ID
                model.setCreaterName(user.getUserName());// 用户创建名称
                model.setVersion(0);// 创建时，模型版本默认为0
                model.setIsTableCreate(0);// 是否创建表 默认为否“0”
                model.setIsJspCreate(0);// 是否创建页面 默认为否“0”
                model.setIsMenuCreate(0);
                model.setStatus("0");// 创建时，状态默认为“0”
                model.setIsSubtable(0);
                model.setModelName(modelName);
                model.setClassType(oldModel.getClassType());
                model.setModelType(oldModel.getModelType());
                model.setMaintableId("");
                model.setModelDesc(oldModel.getModelDesc());
                model.setIsMoreView(0);
                if ("0".equals(oldModel.getModelType())) {//主数据
                    model.setIsWorkflow(1);
                    model.setIsModify(1);
                    model.setIsDispatch(1);
                } else {//字典
                    model.setIsWorkflow(0);
                    model.setIsModify(0);
                    model.setIsDispatch(0);
                }

                int count = modelService.insertModel(model);
                if (count > 0) {//创建成功
                    Map<String, Object> params = new HashMap<>();
                    params.put("oldId", oldModelId);
                    params.put("id", model.getId());
                    attributeServiceImp.copyAttrubute(params);
                }
                jsonObject.put("msg", "success");
            }


        } catch (Exception e) {
            jsonObject.put("msg", "false");
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * 导出属性模板
     *
     * @return
     */
    @RequestMapping(value = "standService", method = RequestMethod.POST)
    @ResponseBody
    public void standService(HttpServletResponse response, HttpServletRequest request) {
        try {
            String modelId = request.getParameter("modelId");
            String modelName = modelService.selectByPk(modelId).getModelName();
            String path = getClass().getClassLoader().getResource("").getPath();
            String rootPath = "";
            if ("\\".equals(File.separator)) {
                rootPath = path.substring(1, path.indexOf("/WEB-INF/classes"));
                rootPath = rootPath.replace("/", "\\");
            }
            rootPath += "/standService";
            System.out.println("path:" + rootPath);
            File file = new File(rootPath);
            if (!file.exists() && !file.isDirectory())
                file.mkdir();
            String fileName = modelName + "标准服务端接口.wsdl";
            String filePath = rootPath + "/" + fileName;

            File file2 = new File(filePath);
            if (!file2.exists())
                file2.createNewFile();
            FileWriter fileWriter = new FileWriter(filePath);
            for (int i = 0; i < StandService.serviceContent().size(); i++) {
                fileWriter.write(StandService.serviceContent().get(i) + "\r\n");
                if (StandService.serviceContent().get(i).equals("<xs:sequence>")) {
                    List<AttrConfig> las = cacheUtil.getAttrList(modelId);
                    for (AttrConfig attr : las) {
                        fileWriter.write("<xs:element minOccurs=\"0\" \"name=\"" + attr.getAttrColumn() + " nillable=\"true\" type=\"xs:string\"/>" + "\r\n");
                    }
                }
            }
            fileWriter.flush();
            fileWriter.close();  //文件写入完毕

            //读取下载文件
            InputStream inStream = new FileInputStream(filePath);
            if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0 || request.getHeader("User-Agent").toUpperCase().indexOf("RV:11.0") > 0) {
                fileName = URLEncoder.encode(fileName, "UTF-8");//IE浏览器
            } else {
                fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");//firefox浏览器
            }
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream; charset=UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
            // 循环取出流中的数据
            byte[] b = new byte[100];
            int len;
            OutputStream output = response.getOutputStream();
            while ((len = inStream.read(b)) > 0)
                output.write(b, 0, len);

            output.flush();
            output.close();
            inStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
